public class Solution3 {
    public int m;
    public int n;
    public boolean[][] visit;
    public int count;
    public int sum;
    public int ret;
    public int[] dx = {0, 0, 1, -1};
    public int[] dy = {1, -1, 0, 0};

    public int uniquePathsIII(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        visit = new boolean[m][n];
        int x = 0;
        int y = 0;

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    x = i;
                    y = j;
                }else if( grid[i][j] == 0) {
                    sum++;
                }
            }
        }
        sum++;

        visit[x][y] = true;
        dfs(grid, x, y);
        return ret;
    }

    public void dfs(int[][] grid, int i, int j) {
        if(grid[i][j] == 2) {
            if(count == sum) {
                ret++;
            }
            return;
        }

        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && grid[x][y] != -1) {
                visit[x][y] = true;
                count++;
                dfs(grid, x, y);
                visit[x][y] = false;
                count--;
            }
        }
    }
}
